<template>
  <div class="dialog-score">
    <div class="dialog-toolbar">
      <div class="title">综合评分数据 - 所有支行</div>
      <button class="btn-export" :disabled="!scoreResult" @click="exportToExcel">📥 导出Excel</button>
    </div>

    <div v-if="!scoreResult" class="empty">暂无数据</div>

    <div v-else class="branches">
      <div 
        v-for="branch in sortedBranches" 
        :key="branch.orgNo" 
        class="branch-card"
      >
        <div class="card-header">
          <div class="left">
            <div class="name">{{ getOrgName(branch.orgNo) }} ({{ branch.orgNo }})</div>
            <div class="meta">
              <span>指标数: {{ Object.keys(branch.data.scores).length }}</span>
              <span>排名: {{ branch.data.rank }}</span>
            </div>
          </div>
          <div class="right">
            <div class="score">加权分总和: {{ branch.data.weightedScore.toFixed(2) }}</div>
          </div>
        </div>

        <div class="abnormal" v-if="getAbnormalIndicators(branch.orgNo).length > 0">
          <div class="abnormal-title">🔍 异常指标明细（Z-score > 1 或 < -1）：</div>
          <div class="abnormal-list">
            <div 
              v-for="item in getAbnormalIndicators(branch.orgNo)" 
              :key="item.key" 
              class="abnormal-item"
              :class="item.type"
            >
              <span class="indicator-name">{{ item.name }}</span>
              <span class="indicator-value">值: {{ item.value }}</span>
              <span class="indicator-zscore" :class="item.zScoreClass">Z-score: {{ item.zScore }}</span>
              <span class="indicator-score">得分: {{ item.score }}分</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed } from 'vue'
import { useComprehensiveScore } from '../composables/useComprehensiveScore.js'

const props = defineProps({
  sharedData: {
    type: Object,
    required: true
  }
})

// 仅用于机构名称显示
const { getOrgName } = useComprehensiveScore()

const scoreResult = computed(() => props.sharedData?.scoreResult || null)

const sortedBranches = computed(() => {
  if (!scoreResult.value) return []
  return Object.entries(scoreResult.value.branches)
    .map(([orgNo, data]) => ({ orgNo, data }))
    .sort((a, b) => (b.data.weightedScore || 0) - (a.data.weightedScore || 0))
})

const getAbnormalIndicators = (orgNo) => {
  if (!scoreResult.value) return []
  const data = scoreResult.value.branches[orgNo]
  const list = []
  Object.entries(data.scores || {}).forEach(([key, scoreInfo]) => {
    const z = Number(scoreInfo.zScore)
    const isPositive = scoreInfo.isPositive // 获取指标的正向/负向属性
    if (!isNaN(z) && (z > 1 || z < -1)) {
      // 根据指标正向/负向属性判断类型：
      // 正向指标：Z-score > 1 表示优秀，Z-score < -1 表示风险
      // 负向指标：Z-score > 1 表示风险，Z-score < -1 表示优秀
      let type, zScoreClass
      if (isPositive) {
        // 正向指标
        type = z > 1 ? 'excellent' : 'high-risk'
        zScoreClass = z > 1 ? 'zscore-high' : 'zscore-low'
      } else {
        // 负向指标
        type = z > 1 ? 'high-risk' : 'excellent'
        zScoreClass = z > 1 ? 'zscore-high' : 'zscore-low'
      }
      
      list.push({
        key,
        name: scoreInfo.name,
        value: scoreInfo.originalValue,
        zScore: z,
        score: scoreInfo.score,
        type: type,
        zScoreClass: zScoreClass,
        isPositive: isPositive
      })
    }
  })
  // 绝对值大到小
  return list.sort((a, b) => Math.abs(b.zScore) - Math.abs(a.zScore))
}

// 简化版导出，仅导出“总得分/总排名”两张表
const exportToExcel = async () => {
  try {
    if (!window.XLSX) {
      await new Promise((resolve, reject) => {
        const s = document.createElement('script')
        // 根据环境选择路径
        if (import.meta.env.PROD) {
          s.src = '/coolv/vfs/root/products/ebi/sys/coolrpt/coolresource/libs/xlsx.full.min.js'
        } else {
          s.src = '/libs/xlsx.full.min.js'
        }
        s.onload = resolve
        s.onerror = reject
        document.body.appendChild(s)
      })
    }
    const wb = window.XLSX.utils.book_new()

    // 总得分
    const scoreSheet = [['机构号', '机构名', '加权分总和', '排名']]
    sortedBranches.value.forEach(({ orgNo, data }) => {
      scoreSheet.push([orgNo, getOrgName(orgNo), Number(data.weightedScore || 0), data.rank])
    })
    const wsScore = window.XLSX.utils.aoa_to_sheet(scoreSheet)
    window.XLSX.utils.book_append_sheet(wb, wsScore, '总得分')

    // 总排名（按加权分）
    const rankSheet = [['排名', '机构号', '机构名', '加权分总和']]
    sortedBranches.value.forEach(({ orgNo, data }, idx) => {
      rankSheet.push([idx + 1, orgNo, getOrgName(orgNo), Number(data.weightedScore || 0)])
    })
    const wsRank = window.XLSX.utils.aoa_to_sheet(rankSheet)
    window.XLSX.utils.book_append_sheet(wb, wsRank, '总排名')

    window.XLSX.writeFile(wb, `综合评分_${props.sharedData?.bussDate || ''}.xlsx`)
  } catch (e) {
    console.error('[导出Excel] 失败:', e)
    alert('导出失败，请重试')
  }
}
</script>

<style scoped>
.dialog-score { padding: 0; }
.dialog-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: rgba(255,255,255,0.7);
  border-bottom: 1px solid rgba(0,0,0,0.06);
}
.dialog-toolbar .title { font-size: 18px; font-weight: 600; color: #1a1a1a; }
.btn-export {
  padding: 8px 16px;
  background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
  color: white;
  border: none; border-radius: 4px; cursor: pointer;
}
.branches { padding: 16px; display: flex; flex-direction: column; gap: 16px; }
.branch-card { 
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
  border-radius: 10px; 
  overflow: hidden; 
  box-shadow: 0 10px 24px rgba(18, 28, 80, 0.25);
}
.card-header { display: flex; justify-content: space-between; align-items: center; padding: 14px 16px; color: white; }
.card-header .name { font-size: 16px; font-weight: 600; }
.card-header .meta { opacity: 0.9; display: flex; gap: 12px; font-size: 12px; }
.card-header .score { font-weight: 600; }

.abnormal { 
  margin: 10px 12px 14px; 
  padding: 12px; 
  background: linear-gradient(135deg, rgba(255,255,255,0.08) 0%, rgba(255,255,255,0.03) 100%);
  border-left: 4px solid #ff6b6b; 
  border-radius: 10px; 
  color: #eef2ff;
}
.abnormal-title { 
  font-size: 14px; 
  font-weight: 700; 
  color: #ff6b6b !important; 
  margin-bottom: 8px; 
}
.abnormal-list { 
  display: flex; 
  flex-wrap: wrap; 
  gap: 8px; 
}
.abnormal-item { 
  display: flex; 
  align-items: center; 
  gap: 10px; 
  padding: 12px 14px; 
  background: #2f315e; /* 深色底，提升对比 */
  border: 1px solid #454a86; 
  border-radius: 12px; 
  font-size: 13px; 
  color: #f2f5ff; /* 默认文本白一点 */
  box-shadow: 0 6px 14px rgba(17, 22, 60, 0.25);
}
.abnormal-item .indicator-name { 
  font-weight: 700; 
  color: #eaf0ff; 
  background: rgba(255,255,255,0.12);
  border: 1px solid rgba(255,255,255,0.18);
  padding: 6px 10px;
  border-radius: 8px;
}
.abnormal-item .indicator-value { 
  color: #cfd6ff; 
  font-weight: 600;
}
.abnormal-item .indicator-zscore { 
  font-weight: 700; 
  padding: 4px 10px; 
  border-radius: 14px; 
  font-family: monospace; 
  border: 1px solid transparent;
}
.abnormal-item .indicator-zscore.zscore-high { 
  background: #fddddf;  /* 略深以提升对比 */
  color: #ad1f16; 
  border-color: #ef9aa2;
}
.abnormal-item .indicator-zscore.zscore-low { 
  background: #cfead6; 
  color: #0e5e2d; 
  border-color: #a1d4b7;
}
.abnormal-item .indicator-score { 
  color: #8a6d00;       /* 深金色文字 */
  font-size: 12px; 
  font-weight: 700; 
  background: #fff4cc;  /* 柔和金色底 */
  padding: 4px 10px; 
  border-radius: 14px; 
  border: 1px solid #ffe69c;
}
.empty { padding: 20px; color: #666; }

/* 解决全局 `#app * { color:#fff !important; }` 造成文字全白问题
   使用包含 #app 的更高特异性选择器，并带 !important 进行覆写，仅作用于对话框范围 */
:deep(#app) .dialog-score { color: #2b2f42 !important; }
:deep(#app) .dialog-score .abnormal-title { color: #ff6b6b !important; }
:deep(#app) .dialog-score .abnormal-item { color: #2b2f42 !important; }
:deep(#app) .dialog-score .abnormal-item .indicator-name { color: #2e43c1 !important; }
:deep(#app) .dialog-score .abnormal-item .indicator-value { color: #60647a !important; }
:deep(#app) .dialog-score .abnormal-item .indicator-zscore.zscore-high { color: #d93025 !important; }
:deep(#app) .dialog-score .abnormal-item .indicator-zscore.zscore-low { color: #188038 !important; }
:deep(#app) .dialog-score .abnormal-item .indicator-score { color: #8a6d00 !important; }
</style>


